const auth = require('../middlewares/auth')
const redis = require('../config/redis')
const Router = require('koa-router')
const Comments = require('../models/Comments')
const { Op } = require('sequelize')
const fs = require('fs')
const dayjs = require('dayjs')
const { isEmpty } = require('../utils/verify')
const { ValidationError, NotFoundError } = require('../utils/customError')
const { getCommentsWithCache, fetchVisitorComments } = require('../services/commentService')
const router = new Router()

router.prefix('/comments')
const data = fs.readFileSync('bannedWords.txt', 'utf8')
// 转成数组
const bannedWords = data.split('\n').map((word) => word.trim())
// 创建评论
router.post('/create', async (ctx) => {
  const data = ctx.request.body
  console.log(data)

  if (isEmpty(data.content)) {
    throw new ValidationError('评论内容不能是空的')
  }
  if (isEmpty(String(data.postId))) {
    throw new ValidationError('评论文章ID不能是空的')
  }
  // 同一IP 5分钟内只能评论3次
  const count = await Comments.count({
    where: {
      ip: ctx.ip,
      createdAt: { [Op.gt]: dayjs().subtract(5, 'minutes').toDate() },
    },
  })
  if (count >= 3) {
    throw new ValidationError('同一IP 5分钟内只能评论3次')
  }
  // 读取文件敏感词
  // bannedWords.push(...file.split('\n').map(word => word.trim()));
  if (bannedWords.some((word) => data.content.includes(word))) {
    // 替换成 * 其他内容不变
    bannedWords.forEach((word) => {
      data.content = data.content.replace(new RegExp(word, 'g'), '*')
    })
  }
  // 验证父评论是否存在
  if (data.parentId) {
    const parentComment = await Comments.findOne({
      where: { id: data.parentId || 0, postId: data.postId },
    })
    if (!parentComment) throw new NotFoundError('父评论不存在')
  }
  const result = await Comments.create({
    ...data,
    // content: data.content.replace(/<[^>]*>/gm, ''),
    ip: ctx.ip,
    device: ctx.headers['user-agent'],
  })
  // 评论提交后的缓存清除
  // await redis.del(`post:comments:tree:${data.postId}`);
  ctx.body = {
    code: 200,
    data: result,
  }
})

// 获取文章下的评论树
router.get('/:id/posts', async (ctx) => {
  // Redis键名格式（文章ID作为后缀）
  const postId = ctx.params.id
  if (!postId) {
    return (ctx.body = {
      code: 422,
      data: { message: '文章ID不能是空的' },
    })
  }
  let result = await getCommentsWithCache(postId)
  ctx.body = {
    code: 200,
    data: result,
  }
})
router.get('/list', async (ctx) => {
  const { page = 1, pageSize = 10, key = '', status } = ctx.query
  let where = {}
  if (key) {
    where.content = {
      [Op.like]: `%${key}%`,
    }
  }
  if (status) {
    where.status = status
  }

  const offset = (Number.parseInt(page) - 1) * Number.parseInt(pageSize)
  const result = await fetchVisitorComments(Number.parseInt(pageSize), offset, where)
  const total = await Comments.count()
  ctx.body = {
    code: 200,
    data: { total, data: result },
  }
})
// 审核评论
router.post('/:id/status/:status', auth, async (ctx) => {
  const { id, status } = ctx.params
  const comment = await Comments.findOne({ where: { id } })
  if (!comment) {
    return (ctx.body = { code: 404, data: { message: '评论不存在' } })
  }
  try {
    await comment.update({ status })
    ctx.body = {
      code: 200,
      data: true,
    }
  } catch (error) {
    return (ctx.body = { code: 500, data: { message: error.message } })
  }
})
// 评论删除
router.post('/delete/:id', auth, async (ctx) => {
  const { id } = ctx.params
  const comment = await Comments.findOne({ where: { id } })
  if (!comment) throw new NotFoundError('评论不存在')
  let newVar = await comment.destroy()
  if (!newVar) throw new Error('删除失败,请稍后重试')
  ctx.body = {
    code: 200,
    data: true,
  }
})
// 批量审核评论
router.post('/batchStatus', auth, async (ctx) => {
  const { ids, status } = ctx.request.body
  if (!ids || !status) {
    return (ctx.body = { code: 422, data: { message: '参数错误' } })
  }
  try {
    await Comments.update({ status }, { where: { id: ids } })
    ctx.body = {
      code: 200,
      data: true,
    }
  } catch (error) {
    return (ctx.body = { code: 500, data: { message: error.message } })
  }
})
// 批量删除评论
router.post('/batchDelete', auth, async (ctx) => {
  const { ids } = ctx.request.body
  if (!ids) {
    return (ctx.body = { code: 422, data: { message: '参数错误' } })
  }
  try {
    await Comments.destroy({ where: { id: ids } })
    ctx.body = {
      code: 200,
      data: true,
    }
  } catch (error) {
    return (ctx.body = { code: 500, data: { message: error.message } })
  }
})
module.exports = router
